using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using wb = System.Windows.Forms.WebBrowser ;
using System.Windows.Forms;
using System.Data;
using mshtml;
using SHDocVw;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using t = System.Timers;
using Thinxoft.XedusLive;
using Xedus.ParallelNetworkDriver.SiteFinder;


namespace Thinxoft.XedusLive
{
	

	/// <summary>
	/// Summary description for Start.
	/// </summary>
	public class Start
	{
		//static variables
		static Start start; 
		static Mutex watch;
		

		//instance variables	
		ShellWindowsClass shells ;
		Hashtable instances;
		string ip;
		XedusSiteFinder keyword;  //fix this
        static wb browser;
		

		public Start()
		{
			shells = new ShellWindowsClass();
			instances = new Hashtable();
            keyword = new XedusSiteFinder();
			//start ie watch
			shells.WindowRegistered+=new DShellWindowsEvents_WindowRegisteredEventHandler(shells_WindowRegistered);
			shells.WindowRevoked+=new DShellWindowsEvents_WindowRevokedEventHandler(shells_WindowRevoked);
			StartShellWatch();
		}

		#region [staticmembers]
		static void Initialize()
		{
			Application.ApplicationExit+=new EventHandler(Application_ApplicationExit);
			Application.ThreadExit+=new EventHandler(Application_ThreadExit);
			Application.ThreadException+=new ThreadExceptionEventHandler(Application_ThreadException);
			watch = new Mutex(true,"watch");


		}

		public static Start Instance
		{
			get
			{
				return Start.start;
			}
		}
		#endregion

		/// <summary>
		/// 
		/// </summary>
		/// <param name="args"></param>
		[STAThread]
		public static void Main(string[] args)
		{
            browser = new wb();
			Initialize();
			if(watch.WaitOne(1,true))
			{
				//start singleton
                
				start = new Start();
                Application.Run();
			}
			else
			{
				
			}
		}

		

		internal void StartShellWatch()
		{			
			foreach(InternetExplorer ie in shells)
			{
				if(!instances.ContainsKey(ie.HWND))
				{									
					ie.BeforeNavigate2+=new DWebBrowserEvents2_BeforeNavigate2EventHandler(ie_BeforeNavigate2);
					ie.DocumentComplete+=new DWebBrowserEvents2_DocumentCompleteEventHandler(ie_DocumentComplete);
					instances.Add(ie.HWND,new IEObject(ie,0));
				}
			}
		}

		public void DoNavigate(string url,InternetExplorer ie)
		{
			object flags = null, target = null, post = null, headers = null;
			ie.Navigate(url,ref flags, ref target, ref post, ref headers);
		}

		public InternetExplorer NavigateTo(string url)
		{
			//create instance
			InternetExplorer ie = new InternetExplorerClass();
			object flags = null, target = null, post = null, headers = null;
			
			//set event handlers								
			ie.BeforeNavigate2+=new DWebBrowserEvents2_BeforeNavigate2EventHandler(ie_BeforeNavigate2);
			ie.DocumentComplete+=new DWebBrowserEvents2_DocumentCompleteEventHandler(ie_DocumentComplete);
			instances.Add(ie.HWND,new IEObject(ie,0));

			//do navigation
			ie.Navigate(url,ref flags, ref target, ref post, ref headers);
			
			return ie;
		}

		/// <summary>
		/// converts a junxion keyword into a url
		/// </summary>
		/// <param name="url"></param>
		/// <returns></returns>
        string Resolve(string url, IEObject ieObj)
        {
            string retval = url;
            try
            {
                Uri uri = new Uri(url);
                switch (uri.Scheme.ToLower())
                {
                    case "http":
                    case "file":
                    case "news":
                    case "mms":
                        break;
                    case "live":
                        retval = keyword.ResolveURL(url);
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
               
            }

            return retval;
        }

		/// <summary>
		/// called when an instance of IE is started
		/// </summary>
		/// <param name="lCookie"></param>
		private void shells_WindowRegistered(int lCookie)
		{
			//called when an ie instance is started
			foreach(InternetExplorer ie in shells)
			{
				if(!instances.ContainsKey(ie.HWND))
				{									
					ie.BeforeNavigate2+=new DWebBrowserEvents2_BeforeNavigate2EventHandler(ie_BeforeNavigate2);
					ie.DocumentComplete+=new DWebBrowserEvents2_DocumentCompleteEventHandler(ie_DocumentComplete);
					instances.Add(ie.HWND,new IEObject(ie,lCookie));
				}
				
			}
		}

		/// <summary>
		/// called when an instance of IE is closed
		/// </summary>
		/// <param name="lCookie"></param>
		private void shells_WindowRevoked(int lCookie)
		{
			//remove id of revoked instance from pool
			foreach(object instance in instances.Values)
			{
				IEObject obj = (IEObject)instance;
				if(obj.Instance == 0)
				{
					int key = obj.IE.HWND;
					instances.Remove(key);
				}
				if(obj.Instance == lCookie)
				{
					int key = obj.IE.HWND;
					instances.Remove(key);
				}
			}
		}


		private void ie_BeforeNavigate2(object pDisp, ref object URL, ref object Flags, ref object TargetFrameName, ref object PostData, ref object Headers, ref bool Cancel)
		{
			IEObject ieObj = (IEObject)instances[((InternetExplorer) pDisp).HWND];
			InternetExplorer ie = ieObj.IE;			
		
			string newUrl = Resolve((string)URL,ieObj );
			if(newUrl != (string)URL)
			{
				DoNavigate(newUrl,ie);
			}
			
		}

        private void ie_DocumentComplete(object pDisp, ref object URL)
        {
            IEObject ieObj = (IEObject)instances[((InternetExplorer)pDisp).HWND];
            IHTMLDocument2 doc = (IHTMLDocument2)ieObj.IE.Document;
            try
            {
                doc.location.assign("hhh:");
            }
            catch (Exception ex)
            {

            }
            
//          wb b = (wb)wb.FromChildHandle(new IntPtr(ieObj.IE.HWND));
//          IWebBrowser2 wb4 = (IWebBrowser2)ieObj.IE.Application;
//          
           
//            if (ieObj.Open)
//            {
//                string content = string.Format(@"<html><title>{1}</title>
//                                                     <frameset rows='0%,100%' >
//                                                         <frame src='{0}' frameborder=0 >
//                                                        <frame src='{0}' frameborder=0 >
//                                                      </frameset>
//                                                    </html>", "http://www.84east.com",(string)URL);//<frameset><frame></frame></frameset>


//                IHTMLDocument2 doc = (IHTMLDocument2)ieObj.IE.Document;
               
//                doc.write(content);
               
              
//            }
            
        }

        void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        

		private static void Application_ApplicationExit(object sender, EventArgs e)
		{
			//release the mutex and close the application
			
			
		}

		private static void Application_ThreadExit(object sender, EventArgs e)
		{
			//917 406 5029
			//dispose of any thread related resources
			watch.ReleaseMutex();
		}

		private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
		{
			//handle any thread related errors
		}

	}
}
